import type { Article } from '@/types';
import {
  getMockAllArticles,
  getMockComments,
  addArticleStar,
  addArticleLike,
  cancelArticleStar,
  cancelArticleLike
} from '@/Utils/localForage';

/**
 * @description 获取相关文章 
 */
export const getRelatedArticles = async (currentArticle: Article) => {
  const articles = await getMockAllArticles();
  if (!articles) return [];
  return articles.filter(
    (article) =>
      article.id !== currentArticle.id &&
      article.tags.some((tag) => currentArticle.tags.includes(tag))
  );
};

/**
 * @description 获取最新文章列表
 */
export const getLatestArticles = async () => {
  const articles = await getMockAllArticles();
  if (!articles) return [];
  const now = new Date();
  const fifteenDaysAgo = new Date(now.getTime() - 15 * 24 * 60 * 60 * 1000);
  return articles
    .filter(article => new Date(article.publishTime) >= fifteenDaysAgo)
    .sort((a, b) => new Date(b.publishTime).getTime() - new Date(a.publishTime).getTime());
};

/**
 * @description 获取热门文章
 */
export const getHotArticles = async () => {
  const articles = await getMockAllArticles();
  if (!articles) return { techHotList: [], compreHotList: [] };
  return {
    techHotList:articles.filter(article=>article.category==='teach').sort((a, b) => b.rank - a.rank).slice(0, 5),
    compreHotList:articles.sort((a, b) => b.rank - a.rank)
  };
}

/**
 * @description 获取当前文章
 */
export const getCurrentArticle = async (id: string) => {
  const articles = await getMockAllArticles();
  if (!articles) return;
  return articles.find((article) => article.id === id);
};

/**
 * @description 收藏当前文章
 */
export const collectCurrentArticle = async (id: string) => {
  await addArticleStar(id);
};

/**
 * @description  取消收藏
 */
export const cancelCollectCurrentArticle = async (id: string) => {
  await cancelArticleStar(id);
};

/**
 * @description 点赞文章
 */
export const addLikeCurrentArticle = async (id: string) => {
  await addArticleLike(id);
};

/**
 * @description 点赞文章
 */
export const cancelLikeCurrentArticle = async (id: string) => {
  await cancelArticleLike(id);
};


/**
 * @description 获取当前文章评论
 */
export const getCurrentArticleComments = async (id: string) => {
  const comments = await getMockComments();
  if (!comments) return [];
  return comments.filter((comment) => comment.articleId === id);
};
